package util

import (
	"MBGAdmin/models"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
)

type MenuStruct struct {
	Id    int
	Name  string
	Level int8
	Icon  string
	TopId int
	Url   string
	Child []*MenuStruct
}

// 根据roleIds获取菜单结构
// level读取几层(适当调整可提升效率)
func GetMenuStructByTopId(roleIds []orm.ParamsList, topId int, level int) []*MenuStruct {
	var menuStruct []*MenuStruct
	var menusAdmin []models.Menus
	_, _ = orm.NewOrm().QueryTable(models.Menus{}).Filter("top_id", topId).Filter("id__in", roleIds).OrderBy("level", "-order", "top_id").All(&menusAdmin)
	// 如果层级数为0则不读取直接返回(减少读库次数,提高效率)
	if level != 0 {
		for _, v := range menusAdmin {
			child := GetMenuStructByTopId(roleIds, v.Id, level-1)
			node := &MenuStruct{
				Id:    v.Id,
				Name:  v.Name,
				Level: v.Level,
				Icon:  v.Icon,
				TopId: v.Top.Id,
				Url:   v.Url,
				Child: child,
			}
			menuStruct = append(menuStruct, node)
		}
	}
	return menuStruct
}

// 根据AdminId和URI验证管理员是否有权限
func VerifyMenuByAdminId(admin models.Admins, uri string) bool {
	subUri := GetSubUriByUri(uri)
	var list []orm.ParamsList
	_, _ = orm.NewOrm().QueryTable(models.RoleMenu{}).Filter("role_id", admin.Role.Id).RelatedSel("menu").ValuesList(&list, "menu__Url")
	list = append(list, orm.ParamsList{"/admin/index/index"})
	list = append(list, orm.ParamsList{"/admin/index/desktop"})
	if strings.Contains(orm.ToStr(list), subUri) {
		return true
	}
	return false
}

// 根据uri获取菜单的分层名称
func GetMenuLevelNameByUri(uri string) (menuName []string) {
	var menu []orm.Params
	_, _ = orm.NewOrm().QueryTable(models.Menus{}).
		Filter("url", GetSubUriByUri(uri)).RelatedSel("Top").Values(&menu, "name", "top__name", "top__top__name")
	if menu != nil {
		if menu[0]["Top__Top__Name"] != nil {
			menuName = append(menuName, menu[0]["Top__Top__Name"].(string))
		}
		if menu[0]["Top__Name"] != nil {
			menuName = append(menuName, menu[0]["Top__Name"].(string))
		}
		if menu[0]["Name"] != nil {
			menuName = append(menuName, menu[0]["Name"].(string))
		}
	}
	return
}

// 根据RoleId和MenuIds设置角色的菜单
func SetRoleMenuByRoleIdAndMenuIds(roleId int, menus string) {
	_, _ = orm.NewOrm().QueryTable(models.RoleMenu{}).Filter("role_id", roleId).Delete()
	var RoleMenu []models.RoleMenu
	for _, s := range strings.Split(menus, ",") {
		if s == "" {
			continue
		}
		menuId, _ := strconv.Atoi(s)
		RoleMenu = append(RoleMenu, models.RoleMenu{
			Role: &models.Roles{Id: roleId},
			Menu: &models.Menus{Id: menuId},
		})
	}
	_, _ = orm.NewOrm().InsertMulti(len(RoleMenu), RoleMenu)
}
